package com.itheima.entry.controller.impl;

import com.itheima.entry.controller.ISuperController;
import com.itheima.entry.dao.SuperSave;
import com.itheima.entry.domain.UserInfo;
import com.itheima.entry.factory.SuperFactory;
import com.itheima.entry.factory.UserFactroy;
import com.itheima.entry.service.ISuperService;
import com.itheima.utils.email.SendEmail;


import java.io.*;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;

public class SuperControllerImpl implements ISuperController {
    private Scanner sc = new Scanner(System.in);
    private static Properties prop = new Properties();
    private DateTimeFormatter fmtProp = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    private ISuperService superService = SuperFactory.getService();
//    private IUserController userController = UserFactroy.getController();


    static {
//        InputStream ss = ClassLoader.getSystemResourceAsStream("D:\\heima_system\\prop\\superProp.properties");
        FileReader   ss = null;
        try {
            ss = new FileReader("D:\\heima_system\\prop\\superProp.properties");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            assert ss != null;
            prop.load(ss);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void login() {


        while (true) {
            //判断是否锁死登录
            if (!accessLogin()) {
                System.out.println("您输入错误次数过多,请消停会再登录");
                return;
            }
            if (!isSuper()) {
                //验证失败,锁死管理员登录系统
                prop.setProperty("access", "false");
                prop.setProperty("time", LocalDateTime.now().format(fmtProp));
                try {
                    prop.store(new FileWriter("D:\\heima_system\\prop\\superProp.properties"), null);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else {     //验证成功

                prop.setProperty("access", "true");
                try {
                    prop.store(new FileWriter("D:\\heima_system\\prop\\superProp.properties"), null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                new Thread(new SuperSave(superService.getAllUsers())).start();
                menu();
            }


        }


    }


    public void menu() {
        while (true) {
            System.out.println("1. 查看用户信息 2. 删除用户 3.修改密码 4.退出");
            switch (sc.next()) {
                case "1":

                    showList(superService.getAllUsers());
                    break;
                case "2":
                    removeUser();
                    break;
                case "3":
                    changePassword();
                    break;
                case "4":
                    System.out.println("啊朋友再见!");
                    UserFactroy.getController().entry();
//                    userController.entry();
                    return;
                default:
                    System.out.println("输入有误");
                    break;
            }
        }


    }

    private void changePassword() {
        System.out.println("请输入需要修改密码的用户名:");
        String username = sc.next();
        if (!superService.isUserExist(username)) {
            System.out.println("输入的用户不存在");
            return;
        }
        System.out.println("请给该用户设置新的密码");
        superService.changePassword(username, sc.next());
        System.out.println("设置成功!");
    }


    //对登录的用户账号密码及邮箱的验证
    private boolean isSuper() {
        int count = 0;
        while (true) {
            System.out.println("请输入超级用户名:");
            String username = sc.next();
            System.out.println("请输入超级用户名密码:");
            String password = sc.next();
            String superUsername = (String) prop.get("superUsername");
            String superPassword = (String) prop.get("superPassword");
            String email = (String) prop.get("email");
            String[] split = email.split("@");
            String maskEmail = split[0].substring(0, 2) + "********@" + split[1];
            String sendRandom = null;
            System.out.println("正在向" + maskEmail + "发送验证码,请稍等...");
            try {
                sendRandom = SendEmail.sendEmail(email);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("已经向管理员邮箱(" + maskEmail + ")发送邮件,请联系管理员索要验证码,或登录邮箱提取验证码,并输入验证码:");
            String inputRandom = sc.next();
            if (username.equals(superUsername) && password.equals(superPassword) && sendRandom.equals(inputRandom)) {
                return true;
            } else {
                count++;
                if (count == 3) {
                    System.out.println("错误次数过多,再见");
                    return false;
                }
                System.out.println("登录/验证失败,请重新登录和验证");
            }
        }

    }


    //允许登录的验证方法 加锁时间
    private boolean accessLogin() {
        String isAccess = (String) prop.get("access");

        if ("true".equals(isAccess)) {
            return true;
        } else {
            String timeString = (String) (prop.get("time"));
            LocalDateTime lockedTime = LocalDateTime.parse(timeString, fmtProp);
            long seconds = Duration.between(lockedTime, LocalDateTime.now()).getSeconds();
//            System.out.println(seconds);
            if (seconds > 30) {//单位:秒
                return true;
            }
        }
        return false;
    }

    //打印所有用户的信息
    private void showList(ArrayList<UserInfo> list) {
        if (list == null || list.size() == 0) {
            System.out.println("暂无用户信息");
            return;
        }
        System.out.println("用户名\t\t密码\t\t邮箱\t\t电话\t\t注册时间\t\t上次登录时间\t\t上次登出时间");
        for (UserInfo user : list) {
            System.out.print(user.getUsername() + "\t" +
                    user.getPassword() + "\t" +
                    user.getEmail() + "\t" +
                    user.getPhone() + "\t");
            if (user.getRegisterDate() == null) {
                System.out.print("无\t@ ");
            } else {
                System.out.print(user.getRegisterDate().format(fmtProp) + "\t@ ");
            }
            if (user.getLoginDate() == null) {
                System.out.print("无\t@ ");
            } else {
                System.out.print(user.getLoginDate().format(fmtProp) + "\t@ ");
            }
            if (user.getExitDate() == null) {
                System.out.print("无\t ");
            } else {
                System.out.print(user.getExitDate().format(fmtProp) + "\t ");
            }
/*            System.out.print(" @@ ");
            if (user.getExportDateList() == null || user.getExportDateList().size() == 0) {
                System.out.print("无");
            } else {
                for (LocalDateTime time : user.getExportDateList()) {
                    System.out.print(time.format(fmtProp) + "\t\t");
                }
            }*/
            System.out.println();
        }

    }


    //删除用户
    private void removeUser() {
        System.out.println("请输入要删除的用户名:");
        String username = sc.next();
        boolean b = superService.removeUser(username);
        if (b) {
            System.out.println("删除成功");
        } else {
            System.out.println("暂无该用户,删除失败");
        }
    }


}
